<script lang="ts">
// 设备——台账管理
export default {
  name: "equipmentPage"
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import { VXETable } from "vxe-table";
import {
  addDevice,
  updateDevice,
  queryDevicePage,
  deleteDevice
} from "/@/api/equipment/archives";
import { queryDeviceTypeAll } from "/@/api/equipment/classify";
import { successMessage, errorMessage } from "/@/utils/message";
import { queryTeamAll } from "/@/api/basic/team";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";
import { ElLoading } from "element-plus";
import { loadEnv } from "@build/index";
import { getToken } from "/@/utils/auth";
const route = useRoute();
const routeName = route.name as string;
// 加载环境变量 VITE_PROXY_DOMAIN（开发环境）  VITE_PROXY_DOMAIN_REAL（打包后的线上环境）
const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL } = loadEnv();
const actionUrl =
  process.env.NODE_ENV === "production"
    ? VITE_PROXY_DOMAIN_REAL
    : (VITE_PROXY_DOMAIN as string);

const getTo = getToken();
const token = JSON.parse(getTo).accessToken as string;
// 上传文件时的token
const myHeaders = reactive({
  Authorization: token
});
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    code: "",
    name: "",
    typeId: ""
  }
});
const upload = ref();
// 查询
const searchEvent = () => {
  const data: any = {};
  Object.assign(data, table.listQuery);
  dialog.codePlan = table.listQuery.code;
  dialog.namePlan = table.listQuery.name;
  dialog.typeIdPlan = table.listQuery.typeId;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  table.loading = true;
  data.typeId == ""
    ? (data.typeId = 0)
    : (data.typeId = table.listQuery.typeId);
  queryDevicePage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
const defaultDate = () => {
  //获取新的时间(2019.4.12）
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = (date.getFullYear() + 1).toString(); //'2019'
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1).toString()
      : (date.getMonth() + 1).toString(); //'04'
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da =
    date.getDate() < 10
      ? "0" + date.getDate().toString()
      : date.getDate().toString(); //'12'
  //字符串拼接，开始时间，结束时间
  let end = year + "-" + month + "-" + da; //当天'2019-04-12'
  dialog.insertForm.warrantyTime = end + " 23:59:59"; //将值设置给插件绑定的数据
};

const deviceStatusSelect = reactive({
  deviceStatusOption: [
    { id: 1, label: "开机" },
    { id: 2, label: "关机" },
    { id: 3, label: "故障" }
  ]
});

const dialog = reactive({
  codePlan: "",
  namePlan: "",
  typeIdPlan: "",
  close: [] as any,
  loading: false,
  submitLoading: false,
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  typeData: [] as any[],
  teamData: [] as any[],
  disabledDate: function (time) {
    return time.getTime() - 8.64e7 < Date.now();
  },
  formLabelWidth: "120px",
  insertForm: {
    brand: "",
    code: "",
    id: 0,
    name: "",
    typeId: "",
    warrantyTime: "",
    deviceNum: 1,
    deviceNumUnit: "台",
    deviceStatus: 1,
    teamCode: "",
    teamName: ""
  },
  formRules: {
    name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
    deviceNum: [
      { required: true, message: "请输入设备数量单位", trigger: "blur" }
    ],
    deviceNumUnit: [
      { required: true, message: "请输入设备数量单位", trigger: "blur" }
    ],
    typeId: [{ required: true, message: "请选择设备分类", trigger: "blur" }],
    teamName: [{ required: true, message: "请选择责任部门", trigger: "blur" }],
    deviceStatus: [
      { required: true, message: "请选择设备状态", trigger: "blur" }
    ]
  }
});
// 查询所有设备分类
const queryDeviceType = () => {
  queryDeviceTypeAll().then((res: any) => {
    if (res.code === 0) {
      dialog.typeData = res.data;
    }
  });
};
const insertForm = ref<InstanceType<typeof ElForm>>();
// 新增
const insertEvent = () => {
  defaultDate();
  dialog.selectRow = null;
  dialog.showEdit = true;
};
const getTeamCode = () => {
  dialog.insertForm.teamCode = "";
  if (dialog.insertForm.teamName) {
    var arr = dialog.teamData.filter(
      item => item.name == dialog.insertForm.teamName
    )[0];
    dialog.insertForm.teamCode = arr.code;
  }
};
// 修改
const editEvent = (row: any) => {
  Object.keys(dialog.insertForm).forEach(key => {
    console.log(key);
    dialog.insertForm[key] = row[key];
  });
  dialog.selectRow = row;
  dialog.showEdit = true;
};
// 表单提交
const submitEvent = () => {
  insertForm.value.validate(valid => {
    if (valid) {
      dialog.submitLoading = true;
      if (dialog.selectRow) {
        // 修改
        updateDevice(dialog.insertForm)
          .then((res: any) => {
            if (res.code === 0) {
              successMessage("操作成功");
              handleClose();
              searchEvent();
            } else {
              errorMessage(res.message);
              dialog.submitLoading = false;
            }
          })
          .catch(() => {
            errorMessage("操作失败");
            dialog.submitLoading = false;
          });
      } else {
        // 新增
        addDevice(dialog.insertForm)
          .then((res: any) => {
            if (res.code === 0) {
              successMessage("操作成功");
              handleClose();
              searchEvent();
            } else {
              errorMessage(res.message);
              dialog.submitLoading = false;
            }
          })
          .catch(() => {
            errorMessage("操作失败");
            dialog.submitLoading = false;
          });
      }
    }
  });
};
// 删除设备
const deleteData = async (id: any) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    deleteDevice(id).then((res: any) => {
      if (res.code === 0) {
        searchEvent();
        successMessage("删除成功");
      } else {
        errorMessage(res.message);
      }
    });
  }
};
//下载数据
const upPlan = () => {
  window.open(
    actionUrl +
      `/device/downloadDeviceType?code=${dialog.codePlan}&name=${dialog.namePlan}&typeId=${dialog.typeIdPlan}`
  );
};
//下载设备分类数据
const upClass = () => {
  window.open(actionUrl + "/device/downloadTemplete");
};
//上传设备分类数据
// 文件上传成功
const fileSuccess = (data, res) => {
  if (res.response.code != 500) {
    console.log(res.response, "上传数据");
    setTimeout(() => {
      dialog.close.close();
    }, 1000);
    successMessage("上传成功");
    upload.value.clearFiles();
  } else {
    setTimeout(() => {
      dialog.close.close();
    }, 1000);
    errorMessage(res.response.message);
  }

  searchEvent();
};
// 文件上传失败
const fileError = () => {
  errorMessage("上传失败");
};
// 文件上传前
const fileBefore = file => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  const whiteList = ["xlsx", "xls"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    errorMessage("传文件只能是xlsx,xls格式");
    return false;
  }

  dialog.close = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  dialog.loading = true;
};
const handleClose = () => {
  nextTick(() => {
    dialog.insertForm = {
      brand: "",
      code: "",
      id: 0,
      name: "",
      typeId: "",
      warrantyTime: "",
      deviceNum: 1,
      deviceNumUnit: "台",
      deviceStatus: 1,
      teamCode: "",
      teamName: ""
    };
    insertForm.value.resetFields();
    dialog.submitLoading = false;
    dialog.showEdit = false;
  });
};
// 获取所有班组
const getTeam = () => {
  queryTeamAll().then((res: any) => {
    if (res.code === 0) {
      dialog.teamData = res.data;
    }
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    searchEvent();
    getTeam();
    queryDeviceType();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="设备名称" field="name" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.name"
            placeholder="请输入设备名称"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="设备编号" field="code" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.code"
            placeholder="请输入设备编号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="设备分类" field="typeId" :item-render="{}">
        <template #default="{ data }">
          <el-select
            v-model="data.typeId"
            filterable
            clearable
            placeholder="请选择设备分类"
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="item in dialog.typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            status="primary"
            icon="fa fa-search"
            v-auth="routeName + ':search'"
            @click="searchEvent"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-clone"
            v-auth="routeName + ':U9'"
            status="primary"
            >从U9同步</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-plus"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-download"
            @click="upClass"
            v-auth="routeName + ':add'"
            >下载模板</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-download"
            @click="upPlan"
            v-auth="routeName + ':edit'"
            >下载数据</vxe-button
          >
          <el-upload
            ref="upload"
            class="upload-file"
            :headers="myHeaders"
            :action="actionUrl + '/device/upload'"
            v-auth="routeName + ':upload'"
            :limit="1"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="fileSuccess"
            :on-error="fileError"
            :before-upload="fileBefore"
            style="display: contents"
          >
            <vxe-button status="primary" icon="fa fa-upload"
              >上传文件</vxe-button
            >
          </el-upload>
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-table
      ref="xTable"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="name" title="设备名称" min-width="160"></vxe-column>
      <vxe-column field="code" title="设备编号" min-width="120"></vxe-column>
      <vxe-column field="brand" title="品牌型号" min-width="120"></vxe-column>
      <vxe-column
        field="typeName"
        title="设备分类"
        min-width="150"
      ></vxe-column>
      <vxe-column field="deviceNum" title="数量" min-width="60"></vxe-column>
      <vxe-column
        field="deviceNumUnit"
        title="单位"
        min-width="60"
      ></vxe-column>
      <vxe-column field="deviceStatus" title="设备状态" min-width="80">
        <template #default="{ row }">
          <span v-if="row.deviceStatus === 1">开机</span>
          <span v-if="row.deviceStatus === 2">关机</span>
          <span v-if="row.deviceStatus === 3">故障</span>
        </template>
      </vxe-column>
      <vxe-column
        field="teamName"
        title="责任部门"
        min-width="100"
      ></vxe-column>
      <vxe-column field="warrantyTime" title="保修截止日期" min-width="120">
        <template #default="{ row }">
          {{ row.warrantyTime ? row.warrantyTime.split(" ")[0] : "" }}
        </template>
      </vxe-column>
      <vxe-column title="操作" width="160" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="editEvent(row)"
            v-auth="routeName + ':edit'"
            >编辑</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-trash-o"
            v-auth="routeName + ':delete'"
            @click="deleteData(row.id)"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      :current-page="page.pageNum"
      :page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>

    <!-- 表单弹框 -->
    <el-dialog
      v-model="dialog.showEdit"
      :title="dialog.selectRow ? '编辑&保存' : '新增&保存'"
      width="500px"
      top="7vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="insertForm"
        id="insertForm"
        :model="dialog.insertForm"
        :rules="dialog.formRules"
        :label-width="dialog.formLabelWidth"
      >
        <el-form-item prop="name" label="设备名称">
          <el-input
            v-model="dialog.insertForm.name"
            size="small"
            placeholder="请输入设备名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" label="设备编号">
          <el-input
            v-model="dialog.insertForm.code"
            size="small"
            placeholder="请输入设备编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="brand" label="品牌型号">
          <el-input
            v-model="dialog.insertForm.brand"
            size="small"
            placeholder="请输入品牌型号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="typeId" label="设备分类">
          <el-select
            v-model="dialog.insertForm.typeId"
            filterable
            size="small"
            placeholder="请选择设备分类"
          >
            <el-option
              v-for="item in dialog.typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deviceNum" label="设备数量">
          <el-input-number
            readonly
            type="integer"
            v-model="dialog.insertForm.deviceNum"
            size="small"
            :max="1"
            :min="1"
            placeholder="请输入设备数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="deviceNumUnit" label="设备数量单位">
          <el-input
            readonly
            v-model="dialog.insertForm.deviceNumUnit"
            size="small"
            placeholder="请输入设备数量单位"
          ></el-input>
        </el-form-item>

        <el-form-item prop="deviceStatus" label="设备状态">
          <el-radio-group v-model="dialog.insertForm.deviceStatus">
            <el-radio
              v-for="item in deviceStatusSelect.deviceStatusOption"
              :key="item.id"
              :label="item.id"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="责任部门" prop="teamName" min-width="150">
          <el-select
            v-model="dialog.insertForm.teamName"
            filterable
            placeholder="请选择"
            size="small"
            @change="getTeamCode"
            style="width: 100%"
          >
            <el-option
              v-for="item in dialog.teamData"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="warrantyTime" label="保修截止日期">
          <!-- !userType&&!insertType -->
          <el-date-picker
            v-model="dialog.insertForm.warrantyTime"
            type="date"
            size="small"
            value-format="YYYY-MM-DD 00:00:00"
            clearable
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" size="small">取 消</el-button>
          <el-button
            type="primary"
            size="small"
            @click="submitEvent"
            :disabled="dialog.submitLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.keyword-lighten {
  color: #000;
  background-color: #ffff00;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

// .vxe-button.type--button:not(.is--round) {
//   border-radius: 0;
// }

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
:deep(.vxe-modal--wrapper.type--modal .vxe-modal--body),
:deep(.vxe-modal--wrapper.type--modal .vxe-modal--body .vxe-modal--content) {
  overflow: inherit;
}
#insertForm .el-date-editor.el-input__inner,
#insertForm .el-form-item :deep(.el-date-editor.el-input),
#insertForm .el-select,
#insertForm .el-input-number {
  width: 100% !important;
}
</style>
